package thread_order_print;

public class OrderPrint {
    private int number = 1;
    private final int MAX_NUMBER = 20;

    public synchronized void printNumber(int numberToPrint) throws InterruptedException {
        while (number != numberToPrint) {
            wait(); // 当前线程等待，直到其他线程调用notify()或notifyAll()
        }
        System.out.println(Thread.currentThread().getName() + " prints " + number);
        number++; // 打印后递增number
        notifyAll(); // 唤醒所有等待的线程
    }

    public static void main(String[] args) {
        OrderPrint printer = new OrderPrint();

        // 创建多个线程来打印数字
        for (int i = 1; i <= 20; i++) {
            int numberToPrint = i;
            Thread thread = new Thread(() -> {
                try {
                    printer.printNumber(numberToPrint);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }, "Thread-" + numberToPrint);
            thread.start();
        }
    }
}
